import json
import os
import sys

from PySide6.QtGui import QIcon
from PySide6.QtCore import Slot
from PySide6.QtWidgets import (
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QHeaderView,
    QCheckBox,
    QTableWidgetItem,
)

from queue_sqlite.model import MessageItem

from qfluentwidgets import (
    CardWidget,
    PushButton,
    SearchLineEdit,
    TableWidget,
    setCustomStyleSheet,
)

from .student_dilalog import AddStudentDilalog
from ...style.button_style import ADD_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
from ...signal import global_signals
from ...signal import listen_signals
from ...scheduler_manager import scheduler


def resource_path(relative_path):
    """获取资源的绝对路径"""
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative_path)  # type: ignore
    return os.path.join(os.path.abspath("."), relative_path)


class StudentInterface(QWidget):
    def __init__(self):
        super().__init__()
        self.setObjectName("student_interface")
        self.students = []
        self.setup_ui()

        self.create_signal_slot()
        self.load_data()
        self.populate_table(self.students)

    def create_signal_slot(self):
        global_signals.show_add_dialog_signal.connect(self.show_add_student_dialog)
        listen_signals.listening_students_signal.connect(self.populate_table)

    def setup_ui(self):
        # 设置 title
        self.setWindowTitle("学生管理")
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 50, 20, 20)  # (左, 上, 右, 下)
        card_widget = CardWidget(self)
        buttons_layout = QHBoxLayout(card_widget)

        self.addButton = PushButton("新增", self)
        setCustomStyleSheet(self.addButton, ADD_BUTTON_STYLE, ADD_BUTTON_STYLE)
        self.addButton.clicked.connect(self.add_student)

        self.searchInput = SearchLineEdit(self)
        self.searchInput.setPlaceholderText("搜索学生姓名或学号...")
        self.searchInput.setFixedWidth(500)
        self.batchDeleteButton = PushButton("批量删除", self)
        setCustomStyleSheet(
            self.batchDeleteButton, BATCH_DELETE_BUTTON_STYLE, BATCH_DELETE_BUTTON_STYLE
        )

        buttons_layout.addWidget(self.addButton)
        buttons_layout.addWidget(self.searchInput)
        buttons_layout.addStretch(2)
        buttons_layout.addWidget(self.batchDeleteButton)

        layout.addWidget(card_widget)

        self.table_widget = TableWidget(self)
        self.table_widget.setBorderRadius(8)  # 设置边框圆角
        self.table_widget.setBorderVisible(True)  # 设置表格边框可见
        table_labels = [
            "",
            "学生ID",
            "姓名",
            "学号",
            "性别",
            "班级",
            "语文",
            "数学",
            "英语",
            "总分",
            "操作",
        ]
        self.table_widget.setColumnCount(len(table_labels))
        self.table_widget.setHorizontalHeaderLabels(table_labels)
        self.table_widget.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeMode.Stretch
        )

        layout.addWidget(self.table_widget)

        self.setStyleSheet("StudentInterface {background: white}")
        self.setWindowIcon(QIcon(resource_path("./resources/images/logo.png")))

    def load_data(self):
        self.students = [
            {
                "student_id": 1,
                "student_name": "张三",
                "student_number": "2024010101",
                "gender": 1,
                "class_name": "1班",
                "chinese_score": 80,
                "math_score": 85,
                "english_score": 90,
                "total_score": 265,
            },
            {
                "student_id": 1,
                "student_name": "张三",
                "student_number": "2024010101",
                "gender": 1,
                "class_name": "1班",
                "chinese_score": 80,
                "math_score": 85,
                "english_score": 90,
                "total_score": 265,
            },
            {
                "student_id": 1,
                "student_name": "张三",
                "student_number": "2024010101",
                "gender": 1,
                "class_name": "1班",
                "chinese_score": 80,
                "math_score": 85,
                "english_score": 90,
                "total_score": 265,
            },
            {
                "student_id": 1,
                "student_name": "张三",
                "student_number": "2024010101",
                "gender": 1,
                "class_name": "1班",
                "chinese_score": 80,
                "math_score": 85,
                "english_score": 90,
                "total_score": 265,
            },
            {
                "student_id": 1,
                "student_name": "张三",
                "student_number": "2024010101",
                "gender": 1,
                "class_name": "1班",
                "chinese_score": 80,
                "math_score": 85,
                "english_score": 90,
                "total_score": 265,
            },
        ]
        scheduler.update_listen_data("students", json.dumps(self.students))

    @Slot(list)
    def populate_table(self, students: list):
        print(f"Received students: {students}")
        self.table_widget.setRowCount(len(students))
        for row, student_info in enumerate(students):
            self.setup_table_row(row, student_info)

    def setup_table_row(self, row, student_info):
        checkbox = QCheckBox()
        checkbox.setStyleSheet("margin: 10px")
        self.table_widget.setCellWidget(row, 0, checkbox)
        for col, key in enumerate(self.students[0].keys()):
            value = student_info.get(key, "")
            if key == "gender":
                value = "男" if value == 1 else "女" if value == 2 else "未知"
            item = QTableWidgetItem(str(value))
            self.table_widget.setItem(row, col + 1, item)

    @Slot(dict)
    def show_add_student_dialog(self, message_dict: dict):
        message = MessageItem.from_dict(message_dict)
        print(f"Received message: {message}")
        print("Creating and showing AddStudentDialog")
        self.addButton.setEnabled(True)
        add_student_dialog = AddStudentDilalog(self)
        if add_student_dialog.exec():
            print("用户点击了添加按钮")
        else:
            print("用户点击了取消按钮")

    def add_student_callback(self, message: MessageItem):
        global_signals.show_add_dialog_signal.emit(message.to_dict())

    def add_student(self):
        self.addButton.setEnabled(False)
        scheduler.send_message(
            MessageItem(content={}, destination="add_student"),
            self.add_student_callback,
        )
